home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 8_3.lha / 8_3 / 8_3_float.c < prev    next >
C/C++ Source or Header  |  1993-08-08  |  858b  |  43 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. / Exercise 8.3
  6. / Read in a floating point value, with error checking
  7. include <stream.h>
  8. include <errno.h>
  9. include <stdlib.h>
  10.  
  11. nt read_double(ostream &out, istream &in, double *val)
  12.  
  13.    // set up flushing of the output stream
  14.    ostream *old = in.tie(&out);
  15.  
  16.    // loop until we get something right
  17.    for ( ; ; out << "Try again\n")
  18. {
  19. out << "Type an floating point number: ";
  20.  
  21. // read a line, including the newline
  22. char buf[256], c;
  23. if (!cin.get(buf, 256))
  24.     {
  25.     in.tie(old);
  26.     return 0;
  27.     }
  28. in.get(c);
  29.  
  30. // check the value
  31. char *p;
  32. errno = 0;
  33. double ret = strtod(buf, &p);
  34. if (*p || (p == buf) || errno)
  35.     continue;
  36.  
  37. // return the value, restoring the old tie first
  38. in.tie(old);
  39. *val = ret;
  40. return 1;
  41. }
  42.  
  43.